import React, { createRef, Component } from 'react';
import { TreeSelect, Button, Modal, Empty, message } from 'antd';
import {
  PlusSquareTwoTone,
  DeleteTwoTone,
  EditTwoTone,
} from '@ant-design/icons';
import './style.less';
import Modify from './modify';
import httpRequest from '@/utils/request';
const { SHOW_PARENT, TreeNode } = TreeSelect;

export interface TreeData {
  collection_name: string;
  id: string;
  children?: TreeData[];
}

export interface CollectionsState {
  modalParams: {
    visible: boolean;
    title: string;
    type: number; // 0删除 1新增 2编辑
  };
  currentTreeNode: {
    defaultValue: string;
    treeDefaultExpandedKeys: string[];
    treeNode: TreeData;
  };
  treeData: TreeData[];
  value: string[];
}

export interface CollectionsProps {
  defaultValue?: string[];
}

class Collections extends Component<CollectionsProps, CollectionsState> {
  Modify!: React.RefObject<Modify>;
  state = {
    value: [],
    modalParams: {
      title: '',
      visible: false,
      type: 0,
    },
    currentTreeNode: {
      defaultValue: '',
      treeDefaultExpandedKeys: [],
      treeNode: {
        collection_name: '',
        id: '',
        children: [],
      },
    },
    treeData: [],
  };

  constructor(props: CollectionsProps) {
    super(props);
    this.Modify = createRef();
    this.setTreeData();
  }

  onChange = (value: string[]) => {
    this.setState({ value });
  };

  setTreeData = async () => {
    try {
      const res = await httpRequest.get('/collection');
      this.setState(() => ({
        treeData: res.data || [],
      }));
    } catch (error) {
      console.error(error);
    }
  };

  openModal = (treeData: TreeData, type: 1 | 2 | 0) => {
    this.setState(() => ({
      modalParams: {
        ...this.state.modalParams,
        type,
        title: '新建类型',
        visible: true,
      },
      currentTreeNode: {
        ...this.state.currentTreeNode,
        defaultValue: treeData?.id || '',
        value: treeData?.id || '',
        treeNode: treeData,
      },
    }));
  };

  onCancel = () =>
    this.setState(() => ({
      modalParams: {
        ...this.state.modalParams,
        visible: false,
      },
    }));

  onOk = async () => {
    try {
      switch (this.state.modalParams.type) {
        case 1: {
          await this.create();
          break;
        }
        case 0: {
          await this.delete();
        }
        case 2: {
          await this.update();
        }
      }
      this.onCancel();
    } catch (error) {}
  };

  create = async () => {
    try {
      await httpRequest.post('/collection', { ...this.Modify.current?.state });
      await this.setTreeData();
      message.success('新增成功');
    } catch (error) {
      console.error(error);
      message.error('新增失败');
    }
  };

  delete = async () => {
    if (this.state.currentTreeNode.treeNode.children.length)
      return message.error('请先删除子标签');
    try {
      await httpRequest.delete(
        `/collection/${this.state.currentTreeNode.defaultValue}`
      );
      await this.setTreeData();
      message.success('删除成功');
    } catch (error) {
      console.error(error);
      message.error('删除失败');
    }
  };

  update = async () => {
    try {
      await httpRequest.put('/collection', {
        ...this.Modify.current?.state,
      });
      await this.setTreeData();
      message.success('修改成功');
    } catch (error) {
      console.error(error);
      message.error('修改失败');
    }
  };

  onTreeExpand = (v: any[]) => {
    this.setState(() => ({
      currentTreeNode: {
        ...this.state.currentTreeNode,
        treeDefaultExpandedKeys: v,
      },
    }));
  };

  renderTreeSelect = (treeData: TreeData[]) => {
    return treeData.map(v => (
      <TreeNode
        key={v.id}
        value={v.id}
        title={
          <div className="tree_node_wrap">
            <div className="title">{v.collection_name}</div>
            <div className="button_group">
              <Button
                onClick={e => {
                  this.openModal(v, 1);
                  e.stopPropagation();
                }}
                className="createCollection"
                size="small"
                icon={<PlusSquareTwoTone />}
                type="text"
              ></Button>
              <Button
                onClick={e => {
                  this.openModal(v, 0);
                  e.stopPropagation();
                }}
                className="createCollection"
                size="small"
                icon={<DeleteTwoTone />}
                type="text"
              ></Button>
              <Button
                onClick={e => {
                  this.openModal(v, 2);
                  e.stopPropagation();
                }}
                className="createCollection"
                size="small"
                icon={<EditTwoTone />}
                type="text"
              ></Button>
            </div>
          </div>
        }
      >
        {!!v.children &&
          Array.isArray(v.children) &&
          v.children.length &&
          this.renderTreeSelect(v.children)}
      </TreeNode>
    ));
  };

  renderModalContent = () => {
    switch (this.state.modalParams.type) {
      case 1: {
        return (
          <Modify
            ref={this.Modify}
            {...this.state.currentTreeNode}
            treeData={this.state.treeData}
            type={this.state.modalParams.type}
          ></Modify>
        );
      }
      case 2: {
        return (
          <Modify
            ref={this.Modify}
            {...this.state.currentTreeNode}
            treeData={this.state.treeData}
            type={this.state.modalParams.type}
          ></Modify>
        );
      }
      case 0: {
        return <p>确定删除？</p>;
      }
    }
  };

  dropdownRender = (originNode: any) => {
    if (this.state.treeData.length) return <>{originNode}</>;
    return (
      <>
        <Empty description={<span>暂无数据</span>}>
          <Button onClick={() => this.openModal({}, 1)} type="primary">
            点此新增
          </Button>
        </Empty>
      </>
    );
  };

  render() {
    const tProps = {
      showSearch: true,
      value: this.state.value,
      onChange: this.onChange,
      treeCheckable: true,
      showCheckedStrategy: SHOW_PARENT,
      placeholder: '请选择分类',
      onTreeExpand: this.onTreeExpand,
    };
    return (
      <div className="collections">
        <TreeSelect {...tProps} dropdownRender={this.dropdownRender}>
          {/* <TreeNode value="" title="请添加第一条"></TreeNode> */}
          {this.renderTreeSelect(this.state.treeData)}
        </TreeSelect>
        ;
        <Modal
          title={this.state.modalParams.title}
          visible={this.state.modalParams.visible}
          onCancel={this.onCancel}
          onOk={this.onOk}
        >
          {this.renderModalContent()}
        </Modal>
      </div>
    );
  }
}

export default Collections;
